package com.dominator.socket;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.utils.JsonUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.encode.Des3Utils;
import com.dominator.utils.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author
 * @ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */

@Component
@ServerEndpoint(value = "/websocket")
@Slf4j
public class WebSocketTools {
    //线程安全的静态变量，表示在线连接数
    private static volatile int onlineCount = 0;

    //用来存放每个客户端对应的WebSocket对象，适用于同时与多个客户端通信
    public static CopyOnWriteArraySet<WebSocketTools> webSocketSet = new CopyOnWriteArraySet<WebSocketTools>();
    //若要实现服务端与指定客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    public static ConcurrentHashMap<Session, Object> webSocketMap = new ConcurrentHashMap<Session, Object>();

    private static RedisUtil ru= RedisUtil.getRu();



    //与某个客户端的连接会话，通过它实现定向推送(只推送给某个用户)
    private Session session;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        webSocketMap.put(session, this); //加入map中
        addOnlineCount();    //
        //--------------群发消息(多用于聊天室场景)
        for (WebSocketTools item : webSocketSet) {
            try {
                item.sendAllMessage("有新连接加入当前在线人数为" + getOnlineCount());
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session closeSession) {
        webSocketSet.remove(this); //从set中删除
        webSocketMap.remove(closeSession); //从map中删除
        subOnlineCount();          //在线数减1
        //--------------群发消息(多用于聊天室场景)
        for (WebSocketTools item : webSocketSet) {
            try {
                item.sendAllMessage("有一连接关闭！当前在线人数为" + getOnlineCount());
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message   客户端发送过来的消息
     * @param mySession 可选的参数
     * @throws Exception
     */
    @OnMessage
    public void onMessage(String message, Session mySession) throws Exception {
          log.info("会话sessionId"+mySession.getId()+"来自客户端的消息:" + message);
          ApiMessage msg= new ApiMessage(ReqEnums.REQ_SUCCESS);
          try {
              Dto dto = JsonUtils.toDto(message);
              dto.put("sessionId",mySession.getId());
              ApplicationContext act = ApplicationContextRegister.getApplicationContext();
              msg=act.getBean(SocketService.class).onMessageService(dto);
          }catch (ApiException e){
              msg =new ApiMessage(e.getCode(),e.getMessage());
          }catch (Exception e){
              msg=new ApiMessage(ReqEnums.SYS_ERROR);
          }finally {
              sendToOne(msg,mySession);
          }
    }


    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("发生错误");
        // error.printStackTrace();
    }


    //给所有客户端发送信息
    public void sendAllMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    //定向发送信息
    public void sendMessage(Session mySession, String message) throws IOException {
        synchronized (this) {
            try {
                if (mySession.isOpen()) {//该session如果已被删除，则不执行发送请求，防止报错
                    mySession.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    public void  sendToOne(ApiMessage msg,Session mySession){
        //推送给单个客户端
        for (Session session : webSocketMap.keySet()) {
              if (session.equals(mySession)) {
                WebSocketTools item = (WebSocketTools) webSocketMap.get(mySession);
                try {
                    item.sendMessage(mySession, Des3Utils.encResponse(msg));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }


    public static void sendToId(ApiMessage msg,String sessionId){
        for (Session session : webSocketMap.keySet()) {
            if (session.getId().equals(sessionId)) {
                WebSocketTools item = (WebSocketTools) webSocketMap.get(session);
                try {
                    item.sendMessage(session, Des3Utils.encResponse(msg));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }









    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketTools.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketTools.onlineCount--;
    }


}
